import json
import os
from datetime import datetime

STATS_FILE = 'app/data/stats.json'

# 确保数据目录存在
os.makedirs(os.path.dirname(STATS_FILE), exist_ok=True)

def load_stats():
    """加载统计数据"""
    try:
        if os.path.exists(STATS_FILE):
            with open(STATS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
    except Exception as e:
        print(f"Error loading stats: {e}")
    
    # 如果文件不存在或出错，返回初始数据
    return {
        'page_visits': {},
        'api_calls': {}
    }

def save_stats(stats):
    """保存统计数据"""
    try:
        with open(STATS_FILE, 'w', encoding='utf-8') as f:
            json.dump(stats, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"Error saving stats: {e}")

def record_visit(page_name):
    """记录页面访问"""
    stats = load_stats()
    if page_name not in stats['page_visits']:
        stats['page_visits'][page_name] = 0
    stats['page_visits'][page_name] += 1
    save_stats(stats)

def record_api_call(api_name):
    """记录API调用"""
    stats = load_stats()
    if api_name not in stats['api_calls']:
        stats['api_calls'][api_name] = 0
    stats['api_calls'][api_name] += 1
    save_stats(stats)

def get_total_visits():
    """获取总访问量"""
    stats = load_stats()
    return sum(stats['page_visits'].values())

def get_api_calls():
    """获取API调用统计"""
    stats = load_stats()
    return stats['api_calls'] 